# -*- coding: utf-8 -*-
# standard
import os
import sys
import json

# third

# local
_P_PATH =  os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)
from functions import *


"""
@Title:   
@File: 导出视频信息.py
@Author: walle 2023年10日26日 14时55分30秒
@Version: 1.0.0
@Desc: 
"""


def export_video_records():
    """

    :param json_name: _description_
    """
    db_session = new_db_session()
    print(f"开始查询视频信息")
    files = db_session.query(MediaFileOrm.key, MediaFileOrm.caption, MediaFileOrm.quality)
    print(f"开始查询片段信息")
    clips = db_session.query(ClipOrm.media_key, ClipOrm.start_time, ClipOrm.end_time)
    db_session.close()
    print(f"开始组合视频数据")
    data = {}
    for file in files:
        data[file.key] = {"caption": file.caption, "clips": [], "quality": file.quality}
    print(f"开始组装片段数据")
    for clip in clips:
        clip_container = data[clip.media_key]["clips"]
        clip_container.append({"start_time": clip.start_time, "end_time": clip.end_time})
    print(f"开始排序clip")
    for _key, value in data.items():
        value['clips'].sort(key=lambda x: (float(x["start_time"]), float(x['end_time'])))

    l = []
    for k, v in data.items():
        v['key'] = k
        l.append(v)
    l.sort(key=lambda x: x['quality'], reverse=True)
    data = {}
    for v in l:
        key = v.pop("key")
        data[key] = v
    dir_path = os.path.dirname(os.path.realpath(__file__))
    json_path = os.path.join(dir_path, "medias.json")
    with open(json_path, mode='w', encoding="utf-8") as fp:
        json.dump(data, indent=4, ensure_ascii=False, fp=fp)
    print(f"共计{len(data)}条记录，文件已保存: {json_path}")




if __name__ == '__main__':
    export_video_records()
    pass